package com.whmskj.xjlhbc.mobile.controller;

import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.domain.Bcsc16SecurityReport;
import com.whmskj.xjlhbc.service.SecurityReportService;
import com.whmskj.xjlhbc.service.IPersonnelManagementDataSheetsService;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
 

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**

 */
@RestController
@RequestMapping("/mobile/security")
public class SecurityReportController {

    @Autowired
    private  SecurityReportService service;
    @Autowired
    private IPersonnelManagementDataSheetsService personnelService;
    @PostMapping("/report")
    @Operation(description = "新增安全上报（兼容对象入参与纯数组URL列表）")
    @ApiResponse(content = @Content(schema = @Schema(implementation = Bcsc16SecurityReport.class)))
    public AjaxResult create(@RequestBody String body) {
        Bcsc16SecurityReport entity = parseRequestBody(body, true);
        Long id = service.create(entity);
        return AjaxResult.success(Collections.singletonMap("id", id));
    }

    @GetMapping("/report/{id}")
    @Operation(description = "安全上报详情")
    public AjaxResult detail(@PathVariable("id") Long id) {
        return AjaxResult.success(service.detail(id));
    }


    @GetMapping("/report/history")
    @Operation(description = "我的全部上报记录（分页，按提交时间降序）")
    public AjaxResult history(@RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "10") int size) {
        String reporter = null;
        try {
            if (StpUtil.isLogin()) {
                String nick = personnelService.getCorpMemberByLogin().getNick();
                reporter = (nick != null && !nick.trim().isEmpty()) ? nick : StpUtil.getLoginIdAsString();
            }
        } catch (Exception ignored) {}
        if (page < 1) page = 1;
        if (size < 1) size = 10;
        int offset = (page - 1) * size;
        List<Bcsc16SecurityReport> results = service.listHistory(reporter, offset, size);
        long total = results == null ? 0 : results.size();
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("page", page);
        data.put("size", size);
        data.put("total", total);
        data.put("results", results);
        return AjaxResult.success(data);
    }

    @GetMapping("/departments")
    @Operation(description = "部门名称列表（按sortSerialNumbers升序）")
    public AjaxResult departments() {
        return AjaxResult.success(service.listSectors());
    }

    @PutMapping("/report/{id}")
    @Operation(description = "修改安全上报（仅当日可修改，兼容对象入参与纯数组URL列表）")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody String body) {
        Bcsc16SecurityReport db = service.detail(id);
        if (db == null) return AjaxResult.error("记录不存在");
        Bcsc16SecurityReport entity = parseRequestBody(body, false);
        entity.setId(id);
        int n = service.update(entity);
        return n > 0 ? AjaxResult.success() : AjaxResult.error("修改失败");
    }

    @DeleteMapping("/report/{id}")
    @Operation(description = "删除安全上报（仅当日可删除）")
    public AjaxResult delete(@PathVariable("id") Long id) {
        int n = service.delete(id);
        return n > 0 ? AjaxResult.success() : AjaxResult.error("删除失败");
    }

    /**
     * 解析请求体，支持纯数组URL列表和对象格式
     * @param body 请求体字符串
     * @param isCreate 是否为创建操作（创建时需要设置所有字段，更新时只设置可修改字段）
     * @return 解析后的实体对象
     */
    private Bcsc16SecurityReport parseRequestBody(String body, boolean isCreate) {
        if (body == null) body = "";
        String trimmed = body.trim();
        Bcsc16SecurityReport entity = new Bcsc16SecurityReport();
        
        if (trimmed.startsWith("[")) {
            // 纯数组：认为是 URL 列表
            java.util.List<java.util.Map<String, Object>> photos = parseUrlArray(trimmed);
            setPhotosToEntity(entity, photos);
        } else if (trimmed.startsWith("{")) {
            // 对象：按字段映射
            try {
                JSONObject obj = JSON.parseObject(trimmed);
                
                // 基础字段（创建时需要设置，更新时不需要）
                if (isCreate) {
                    if (obj.containsKey("dateport")) {
                        Object v = obj.get("dateport");
                        if (v != null) {
                            String s = String.valueOf(v).trim();
                            if (!s.isEmpty()) {
                                try { entity.setDateport(java.time.LocalDate.parse(s)); } catch (Exception ignore) {}
                            }
                        }
                    }
                    if (obj.containsKey("responb")) entity.setResponb(obj.getString("responb"));
                    if (obj.containsKey("reporter")) entity.setReporter(obj.getString("reporter"));
                }
                
                // 可修改字段
                if (obj.containsKey("inspection")) entity.setInspection(obj.getString("inspection"));
                if (obj.containsKey("evaluation")) entity.setEvaluation(obj.getString("evaluation"));
                if (obj.containsKey("amount")) {
                    try { entity.setAmount(new java.math.BigDecimal(String.valueOf(obj.get("amount")))); } catch (Exception ignore) {}
                }
                if (obj.containsKey("remarks")) entity.setRemarks(obj.getString("remarks"));
                if (obj.containsKey("confirmedStatus")) entity.setConfirmedStatus(obj.getString("confirmedStatus"));
                
                // 处理照片
                java.util.List<java.util.Map<String, Object>> photos = parsePhotosFromObject(obj);
                if (!photos.isEmpty()) {
                    setPhotosToEntity(entity, photos);
                }
            } catch (Exception ignore) {}
        }
        
        return entity;
    }

    /**
     * 解析URL数组字符串
     */
    private java.util.List<java.util.Map<String, Object>> parseUrlArray(String jsonArray) {
        java.util.List<java.util.Map<String, Object>> photos = new java.util.ArrayList<>();
        try {
            java.util.List<String> urls = JSONArray.parseArray(jsonArray, String.class);
            if (urls != null) {
                for (String u : urls) {
                    if (u == null) continue;
                    String us = u.trim();
                    if (us.isEmpty()) continue;
                    java.util.Map<String, Object> m = new java.util.LinkedHashMap<>();
                    m.put("url", us);
                    photos.add(m);
                }
            }
        } catch (Exception ignore) {}
        return photos;
    }

    /**
     * 从JSON对象中解析照片
     */
    private java.util.List<java.util.Map<String, Object>> parsePhotosFromObject(JSONObject obj) {
        java.util.List<java.util.Map<String, Object>> photos = new java.util.ArrayList<>();
        // 兼容 photos/incomingPhotos 两种入参
        Object p1 = obj.get("photos");
        Object p2 = obj.get("incomingPhotos");
        Object pv = p1 != null ? p1 : p2;
        
        if (pv instanceof JSONArray) {
            JSONArray arr = (JSONArray) pv;
            for (Object o : arr) {
                if (o == null) continue;
                if (o instanceof JSONObject) {
                    JSONObject jo = (JSONObject) o;
                    String url = jo.getString("url");
                    if (url != null && !url.trim().isEmpty()) {
                        java.util.Map<String, Object> m = new java.util.LinkedHashMap<>();
                        m.put("url", url.trim());
                        photos.add(m);
                    }
                } else {
                    String us = String.valueOf(o).trim();
                    if (!us.isEmpty()) {
                        java.util.Map<String, Object> m = new java.util.LinkedHashMap<>();
                        m.put("url", us);
                        photos.add(m);
                    }
                }
            }
        }
        return photos;
    }

    /**
     * 设置照片到实体对象
     */
    private void setPhotosToEntity(Bcsc16SecurityReport entity, java.util.List<java.util.Map<String, Object>> photos) {
        if (photos == null || photos.isEmpty()) return;
        
        try {
            java.lang.reflect.Method setter = Bcsc16SecurityReport.class.getMethod("setPhotos", java.util.List.class);
            setter.invoke(entity, photos);
        } catch (Exception e) {
            try {
                java.lang.reflect.Field pf = Bcsc16SecurityReport.class.getDeclaredField("photos");
                pf.setAccessible(true);
                pf.set(entity, photos);
            } catch (Exception ignore) {}
        }
    }
}


